package maxheap;

import array.Array;

/**
 * 基于数组的最大堆 完全二叉树 平衡二叉树
 * 索引堆
 * d-ary heap
 * 二项堆
 * 斐波那契堆
 * 广义队列
 *
 * @author: yxyi
 * @mail: yxyi@iflytek.com
 * @date: 2019-01-13
 */
public class MaxHeap<E extends Comparable<E>> {

    private Array<E> data;

    public MaxHeap(int capacity) {
        data = new Array<>(capacity);
    }

    public MaxHeap() {
        data = new Array<>();
    }

    public int getSize() {
        return data.getSize();
    }

    public boolean isEmpty() {
        return data.isEmpty();
    }

    private int parent(int index) {
        if (index == 0) {
            throw new IllegalArgumentException("index-0 doesn't have parent.");
        }
        return (index - 1) / 2;
    }

    private int leftChild(int index) {
        return index * 2 + 1;
    }

    private int rightChild(int index) {
        return index * 2 + 2;
    }

    // 向堆中添加元素sift up
    public void add(E e) {
        data.addLast(e);
        siftUp(data.getSize() - 1);
    }

    private void siftUp(int index) {
        while (index > 0 && data.get(parent(index)).compareTo(data.get(index)) < 0) {
            data.swap(index, parent(index));
            index = parent(index);
        }
    }

    public E findMax() {
        if (data.getSize() == 0) {
            throw new IllegalArgumentException("Can't findMax when heap is empty");
        }
        return data.get(0);
    }

    // 从堆中取出元素sift down
    public E extract() {
        E ret = findMax();
        data.swap(0, data.getSize() - 1);
        data.removeLast();
        siftDown(0);

        return ret;
    }

    private void siftDown(int index) {
        while (leftChild(index) < data.getSize()) {
            int newIndex = leftChild(index);
            if ((newIndex + 1) < data.getSize()
                    && data.get(newIndex + 1).compareTo(data.get(newIndex)) > 0) {
                newIndex += 1;
            }
            if (data.get(index).compareTo(data.get(newIndex)) >= 0) {
                break;
            }
            data.swap(index, newIndex);
            index = newIndex;
        }
    }

    // 替换 extract(),add() 两次O(logn)的操作 直接替换堆顶元素，然后sift down
    public E replace(E e) {
        E ret = findMax();
        data.set(0, e);
        siftDown(0);
        return ret;
    }

    // heapify(任意一个数组堆化) 循环add nlogn；找出最后一个非叶子节点循环sift down n
    public MaxHeap(E[] arr) {
        data = new Array<>(arr);
        for (int i = arr.length - 1; i >= 0; i--) {
            siftDown(i);
        }
    }
}
